<?php

namespace app\common\logic;

use think\facade\Db;

class AdminBase extends CommonBase
{
    public $autoConvertResultTime = true;

	public function getList($params)
	{
        $pk = $this->model->getPk();

        if (isset($this->model->query)) {
            $query = $this->model->query;
        }else {
            $query = $this->model->db();
        }

        // 別名
        $alias = $query->getOptions('alias');
        if ($alias) {
            $alias = reset($alias).'.';
        }
        
        // 默認查詢
        if ( ! empty($params['formdata'])) {
            foreach ($params['formdata'] as $key => $value) {
                if (empty($value)) continue;

                if (strpos($key, '_time_start') !== false) {
                    $query->where($alias.strtr($key, "_start", ""), '>=', $value);
                }elseif (strpos($key, '_time_end') !== false) {
                    $query->where($alias.strtr($key, "_end", ""), '>=', $value);
                }else {
                    $query->where($alias.$key, $value);
                }
            }
        }

        // 默認排序
        if ( ! $query->getOptions('order')) {
            if ( ! empty($this->model->order)) {
                // 使用model类定义的排序
                $query->order($alias.$this->model->order);
            }else {
                // 缺省倒序
                $query->order($alias.$pk.' desc');
            }
        }

        // 简单的可以使用这几个,join不行，所有复杂的就手写吧
        $rows = $query->paginate($params['limit']??10)->toArray();
        // $rows = $query->fetchSql()->select();
        // de($rows);
                            
        // 处理一下时间
        if ( ! empty($this->autoConvertResultTime) && ! empty($rows['data'])) {
            foreach ($rows['data'] as $key => $value) {
                foreach($value as $k => $v) {
                    // 非空就查找
                    if ( ! empty($v) && is_numeric($v) && strlen($v) == 10 && (substr($k, -5) == '_time' || $k == 'time')) {
                        $rows['data'][$key][$k] = date('Y-m-d H:i:s', $v);
                    }
                }
            }
        }

        return $rows;
    }
   
}